(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];
    function init(o){
        $(document).click(function(){
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                var ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    data: productInfo,
                    url:'initStock/add/getProductInfo',
                    cols: [[
                        {field: 'productCode', width: 220, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'},
                        {field: 'directoryName', width: 120, title: '产品目录'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    let data = obj.data;
                    let tableData = table.cache["storageproductstableid"];
                    let deliveryDate = $("#carryTime").val();
                    if(isEmpty(deliveryDate)){
                        deliveryDate = currentDate;
                    }
                    $.each(tableData,function(index,value){
                        if(value.tempId == ids){
                            data.tempId = ids;
                            //金额小计（默认为零）
                            data["moneySubtotal"] = 0;
                            //数量（默认为零）
                            data["productNum"] = 0;
                            //交货日期
                            data["deliveryDate"] = deliveryDate;
                            //海关相关信息
                            if(!isEmpty(data.customsCode)){
                                data = setHSInfo(data);
                            }
                            //配件相关信息
                            //产品编码
                            let productCode = data.productCode;
                            //规格编码
                            let specNo = data.specificationCode;
                            let tempPartsList = [];
                            if(!isEmpty(specNo)){
                                $.ajax({
                                    url: "offer/getProductPartsInfoBySpecNo?specNo=" + specNo + "&productCode=" + productCode,
                                    async:false,
                                    success:function(res){
                                        if(res.status == 200){
                                            for(let i in res.data){
                                                let partTempId = GenNonDuplicateID(3) + (index+1);
                                                res.data[i]["tempId"] = partTempId;
                                                res.data[i]["parentTempId"] = data.tempId;
                                                //成品比例(默认1)
                                                res.data[i]["proportionFinishedProducts"] = 1;
                                                //配件比例(默认1)
                                                res.data[i]["partsFinishedProducts"] = 1;
                                                tempPartsList.push(res.data[i]);
                                            }
                                        }else {
                                            layer.msg("获取信息失败，请稍后再试！", {icon: 5});
                                        }
                                    }
                                });
                            }
                            data["partsList"] = tempPartsList;
                            tableData[index] = data;
                        }
                    });
                    table.reload('storageproductstableid',{data:tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode == 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function(index, values){
            if(values.tempId == ids){
                tableData[index]["productCode"] = value;
                //$(".value_"+values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                info:value
            }});
    }
})(window.jQuery);

var form = layui.form, laydate = layui.laydate, advancePayment = 0, partsParentTempId = "", annexList = [], partsList = [], customsCode =[], upload = layui.upload, table = layui.table, $ = layui.jquery, id = getQueryVariable("id"),fzid=getQueryVariable("fzid");

layui.use(['tableEdit',"selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        laydate=layui.laydate,
        selectInput = layui.selectInput;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    lay('#carryTime').each(function () {
        laydate.render({
            elem: '#carryTime',
            //监听日期被切换
            done: function(value, date){
                //产品明细数据
                let detailList = table.cache["storageproductstableid"];
                for(let i in detailList){
                    detailList[i]["deliveryDate"] = value;
                }
                table.reload('storageproductstableid',{data:detailList});
            }
        });
    });


    //客户信息
    let customerInfo = [];
    //客户所属业务员信息
    let salesmanInfo = [];
    //公司信息
    let companyInfo = [];
    //收款银行信息
    let bankAccountList = [];
    //客户联系人
    let customerContact = [];
    //起运地
    let transitPlace = [];
    //目的地
    let country = [];
    //币种
    let currencyInfo = [];
    //美元编码
    let usdCode = "";
    //美元
    let usdName = "";
    //美金汇率
    let usdRate = "";
    //美金对人名币汇率
    let rmbRate = "";
    //价格术语
    let priceTerms = [];
    //业务模式
    let businessModel = [];
    //付款方式
    let paymentMethod = [];
    //运输方式
    let modeOfTransport = [];
    //单位
    let unitOfQuantity = [];
    //费用类型
    let costType = [];
    //删除的老的附件ID集合
    let deleteAnnexIds = [];


    layer.ready(function () {

        //默认客户名称
        let initName = "RTCO PAK INC";
        let initCode = "FQ0192C";
        setCustomerInfo(initName);
        $("#customerCode").val(initCode);
        $("#customerName").val(initName);
        //获取客户联系人
        getCustomerContactName(initCode);

        getCustomerInfo();

        //获取所有公司信息
        $.ajax({
            url:"receivePayment/getCompanyInfo",
            success:function(data){
                if(data.status == 200){
                    companyInfo = data.data;
                    let initCode = "";
                    let initName = "";
                    for(let i in data.data){
                        if(data.data[i].code == "89asd"){
                            initCode = data.data[i].code;
                            initName = data.data[i].name;
                        }
                        //公司名称
                        $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if(initCode.length > 0){
                        $('#signingCompanyCode').val(initCode);
                        $('#signingCompanyName').val(initName);
                        getBankInfo(initCode);
                    }
                    form.render('select');
                }
            }
        });

        //获取起运地
        $.ajax({
            url:"offer/getTransitPlace",
            success:function(data){
                if(data.status == 200){
                    transitPlace = data.data;
                    for(let i in data.data){
                        $('#transitPlaceCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取国家信息
        $.ajax({
            url:"offer/getCountry",
            success:function(data){
                if(data.status == 200){
                    country = data.data;
                    for(let i in data.data){
                        $('#destinationCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取币种
        $.ajax({
            url:"receivePayment/getCurrencyInfo",
            success:function(data){
                if(data.status == 200){
                    currencyInfo = data.data;
                    for(let i in data.data){
                        if(data.data[i].englishName == "USD"){
                            //美元编码
                            usdCode = data.data[i].code;
                            //美元名称
                            usdName = data.data[i].name;
                            //获取美金兑人名币汇率
                            rmbRate = data.data[i].exchangeRate;

                            $("#rmbRate").val(rmbRate);
                        }else if(data.data[i].englishName == "RMB"){
                            //人名币兑美元汇率
                            usdRate = data.data[i].exchangeRate;
                        }
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if(usdCode.length > 0){
                        //默认USD选中
                        $('#currencyCode').val(usdCode);
                        $('#currency').val(usdName);
                        //美元汇率为1
                        $('#usdRate').val(1);
                    }
                    form.render('select');
                }
            }
        });

        //获取价格术语信息
        $.ajax({
            url:"offer/getPriceTerms",
            success:function(data){
                if(data.status == 200){
                    priceTerms = data.data;
                    for(let i in data.data){
                        $('#priceTermsCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取业务模式信息
        $.ajax({
            url:"offer/getBusinessModel",
            success:function(data){
                if(data.status == 200){
                    let defCode = "";
                    let defName = "";
                    for(let i in data.data){
                        //只有正常模式和海外模式(默认正常模式选中)
                        if("备货入库" == data.data[i].name){
                            defCode = data.data[i].code;
                            defName = data.data[i].name;
                            $('#businessModelCode').append(new Option(data.data[i].name, data.data[i].code));
                            businessModel.push(data.data[i]);
                            break;
                        }
                    }
                    $('#businessModelCode').val(defCode);
                    $('#businessModelName').val(defName);
                    form.render('select');
                }
            }
        });

        //收款类型
        $.ajax({
            url: "receivePayment/getReceivePaymentTypeInfo",
            success: function (data) {
                if (data.status == 200) {
                    paymentMethod = data.data;
                    for(let i in data.data){
                        $('#paymentMethodCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取运输方式
        $.ajax({
            url:"offer/getModeOfTransport",
            async:false,
            success:function(data){
                if(data.status == 200){
                    modeOfTransport = data.data;
                    let modeOfTransportName = "";
                    let modeOfTransportCode = "";
                    for(let i in modeOfTransport){
                        if(modeOfTransport[i].name === "海运"){
                            modeOfTransportName = modeOfTransport[i].name;
                            modeOfTransportCode = modeOfTransport[i].code;
                        }
                        $('#transportCode').append(new Option(modeOfTransport[i].name, modeOfTransport[i].code));
                    }
                    $('#modeOfTransport').val(modeOfTransportName);
                    $('#transportCode').val(modeOfTransportCode);
                    form.render('select');
                }
            }
        });

        //获取数量单位
        $.ajax({
            url:"resourceSamples/getUnitOfQuantityInfo",
            success:function(data){
                if(data.status == 200){
                    unitOfQuantity = data.data;
                }
            }
        });

        //获取海关编码信息
        $.ajax({
            url:"offer/getCustomsCode",
            success:function(data){
                if(data.status == 200){
                    customsCode = data.data;
                }
            }
        });

        //获取费用类型
        $.ajax({
            url:"offer/getCostType",
            success:function(data){
                if(data.status == 200){
                    costType = data.data;
                }
            }
        });

        //客户账期默认为0
        $("#customerAccountingPeriod").val(0);

        //预收款比例默认为0
        $("#advancePaymentRatio").val(0);

        //单号：RTCO-当前操作人英文名称-yyyyMMdd+3位自动
        let billNo = "RTCO-" + user.englishName + "-" + getNowFormatDate(2);
        $("#billNo").val(billNo);
    });

    function getCustomerInfo() {
        $.ajax({
            url: "otherOutStock/getAllUserInfo",
            success: function (data) {
                if (data.status == 200) {
                    salesmanInfo = data.data;
                    for (let i in salesmanInfo) {
                        $("#salesmanCode").append(new Option(salesmanInfo[i].name, salesmanInfo[i].code));
                    }
                    $("#salesmanCode").val(user.code);
                    $("#salesmanName").val(user.name);
                }
            }
        });
    }

    //监听业务员下拉框
    form.on("select(salesmanCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in salesmanInfo){
            if(data.value == salesmanInfo[i].code){
                $('#salesmanName').val(salesmanInfo[i].name);
                break;
            }
        }
    });


    //监听运输方式下拉框
    form.on("select(transportCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in modeOfTransport){
            if(data.value == modeOfTransport[i].code){
                $('#modeOfTransport').val(modeOfTransport[i].name);
            }
        }
    });

    //监听付款方式下拉框
    form.on("select(paymentMethodCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in paymentMethod){
            if(data.value == paymentMethod[i].code){
                $('#paymentMethodName').val(paymentMethod[i].name);
            }
        }
    });

    //监听业务模式下拉框
    form.on("select(businessModelCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in businessModel){
            if(data.value == businessModel[i].code){
                $('#businessModelName').val(businessModel[i].name);
            }
        }
    });

    //监听价格术语下拉框
    form.on("select(priceTermsCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in priceTerms){
            if(data.value == priceTerms[i].code){
                $('#priceTermsName').val(priceTerms[i].name);
            }
        }
    });

    //监听目的地下拉框
    form.on("select(destinationCode)", function(data){
        if(data.value === ""){
            return;
        }
        let name = getDestinationName(data.value);
        $("#destinationName").val(name);
    });

    function getDestinationName(code) {
        for(let i in country){
            if(country[i].code == code){
                return country[i].name;
            }
        }
        return "";
    }

    //监听启运地下拉框
    form.on("select(transitPlaceCode)", function(data){
        if(data.value === ""){
            return;
        }
        let name = transitPlaceCode(data.value);
        $("#transitPlaceName").val(name);
    });

    function transitPlaceCode(code) {
        for(let i in transitPlace){
            if(transitPlace[i].code == code){
                return transitPlace[i].name;
            }
        }
        return "";
    }

    //监听签约公司下拉框
    form.on("select(signingCompanyCode)", function(data){
        if(data.value === ""){
            return;
        }
        let name = getCompanyInfoByCode(data.value);
        $("#signingCompanyName").val(name);
        //重新查询银行信息
        getBankInfo(data.value);
    });

    //监听收款银行名称下拉框
    form.on("select(bankCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in bankAccountList){
            if(data.value == bankAccountList[i].code){
                $("#bankName").val(bankAccountList[i].name);
                break;
            }
        }
    });

    //监听客户联系人下拉框
    form.on("select(customerContactName)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in customerContact){
            if(data.value == customerContact[i].name){
                $('#contactEmail').val(customerContact[i].email);
                form.render();
                break;
            }
        }
    });

    function setCustomerInfo(initData) {
        //客户名称
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })
        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            $.ajax({
                url: "basicInformation/getCustomerInfo?info=" + obj.value,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        customerInfo = res.data.customerInfo;
                        for (let i in customerInfo) {
                            customerInfo[i]["value"] = customerInfo[i].code;
                            tempData.push(customerInfo[i]);
                        }
                    }
                }
            })
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            let name = obj.textContent;
            $("#customerCode").val(code);
            $("#customerName").val(name);
            //获取客户联系人
            getCustomerContactName(code);
            //获取客户等级
            $("#customerLevelName").val("");
            $("#customerLevelCode").val("");
            for(let i in customerInfo){
                if(customerInfo[i].code == code){
                    let customerLevelName = customerInfo[i]["customerLevelName"];
                    let customerLevelCode = customerInfo[i]["customerLevelCode"];
                    if(!isEmpty(customerLevelName)){
                        $("#customerLevelName").val(customerLevelName);
                        $("#customerLevelCode").val(customerLevelCode);
                        break;
                    }
                }
            }
        });
    }


    //监听业务员下拉框
    form.on("select(salesmanCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in salesmanInfo){
            if(data.value == salesmanInfo[i].code){
                $('#salesmanName').val(salesmanInfo[i].name);
                break;
            }
        }
    });

    //监听币种下拉框
    form.on('select(currencyCode)', function (data) {
        if(data.value === ""){
            return;
        }
        let englishName = getCurrencyInfoByCode(data.value, 1);
        if(englishName == "RMB"){
            //如果选择rmb，则对应rmb汇率为1
            $("#rmbRate").val(1);
            $("#usdRate").val(usdRate);
        }else if(englishName == "USD"){
            //如果选择美元，则对应美金汇率为1
            $("#rmbRate").val(rmbRate);
            $("#usdRate").val(1);
        }else{
            //其它
            let exchangeRate = getCurrencyInfoByCode(data.value, 3);
            $("#usdRate").val(exchangeRate);
            $("#rmbRate").val(rmbRate);
        }
        let name = getCurrencyInfoByCode(data.value, 2);
        $("#currency").val(name);
    })

    //获取币种信息：code:编码  type(1:获取英文名称 2:获取name 3:获取汇率)
    function getCurrencyInfoByCode(code, type){
        for(let i in currencyInfo){
            if(currencyInfo[i].code == code){
                let res = "";
                switch (type) {
                    case 1:
                        res = currencyInfo[i].englishName;
                        break;
                    case 2:
                        res = currencyInfo[i].name;
                        break;
                    case 3:
                        res = currencyInfo[i].exchangeRate;
                        break;
                }
                return res;
            }
        }
        return "";
    }


    function getCustomerContactName(customCode) {
        //通过客户编码获取客户联系人
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:customCode,
            url:"otherOutStock/add/getCustomerContactInfo",
            async:false,
            success:function(res){
                if(res.status == 200){
                    customerContact = res.data;
                    //客户联系人重新赋值
                    $("#customerContactName").empty();
                    for(let i in res.data){
                        $('#customerContactName').append(new Option(res.data[i].name, res.data[i].name));
                    }
                    //默认选中第一个
                    if(res.data.length > 0){
                        $('#customerContactName').val(res.data[0].name);
                        $('#contactEmail').val(res.data[0].email);
                    }
                    form.render('select');
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    function getSalesman(code){
        for(let i in customerInfo){
            if(customerInfo[i].code == code){
                $('#salesmanCode').val(customerInfo[i].salesmanCode);
                $('#salesmanName').val(customerInfo[i].salesman);
                break;
            }
        }
    }

    function getCompanyInfoByCode(code){
        for(let i in companyInfo){
            if(companyInfo[i].code == code){
                return companyInfo[i].name;
            }
        }
        return "";
    }

    function getBankInfo(code) {
        //获取银行账号
        let defaultCode = "";
        let defaultName = "";
        $.ajax({
            url:"receivePayment/getBankAccountInfo?code=" + code,
            success:function(res){
                if(res.status == 200){
                    //银行信息
                    bankAccountList = res.data.bankAccountList;
                    $('#bankCode').empty();
                    for(let i in bankAccountList){
                        if(defaultCode.length == 0 && bankAccountList[i].defaultBusinessUse == 1){
                            defaultCode = bankAccountList[i].code;
                            defaultName = bankAccountList[i].name;
                        }
                        $('#bankCode').append(new Option(bankAccountList[i].name + "_" + bankAccountList[i].bankAccount, bankAccountList[i].code));
                    }
                    if(defaultCode.length > 0){
                        $('#bankCode').val(defaultCode);
                        $("#bankName").val(defaultName);
                    }else{
                        $('#bankCode').val(bankAccountList[0].code);
                        $("#bankName").val(bankAccountList[0].name);
                    }

                    form.render('select');
                }
            }
        });
    }




//监听提交
    form.on('submit(form-element)', function (data) {
        //防止重复提交问题
        preventDuplicateSubmissions();
        let indexsl = 0;
        //产品明细数据
        let storageproductsdata = table.cache["storageproductstableid"];
        //费用数据
        let costtabledata = table.cache["costtableid"];
        $.each(storageproductsdata, function (index, value) {
            if (typeof (storageproductsdata[index]["productCode"]) == "undefined" || storageproductsdata[index]["productCode"] == "") {
                layer.msg("产品表第" + (index + 1) + "条产品编码不能为空");
                indexsl++;
                return false;
            } else if (typeof (storageproductsdata[index]["productNum"]) == "undefined" || storageproductsdata[index]["productNum"] == "") {
                layer.msg("产品表第" + (index + 1) + "条数量不能为空");
                indexsl++;
                return false;
            } else if (typeof (storageproductsdata[index]["unitPrice"]) == "undefined" || storageproductsdata[index]["unitPrice"] == "") {
                layer.msg("产品表第" + (index + 1) + "条单价不能为空");
                indexsl++;
                return false;
            }else if (typeof (storageproductsdata[index]["deliveryDate"]) == "undefined" || storageproductsdata[index]["deliveryDate"] == "") {
                layer.msg("产品表第" + (index + 1) + "条要求交货日期不能为空");
                indexsl++;
                return false;
            }else if (typeof (storageproductsdata[index]["productUnitName"]) == "undefined" || storageproductsdata[index]["productUnitName"] == "" || storageproductsdata[index]["productUnitName"] == null) {
                storageproductsdata[index]["productUnitName"] = getProductUnitCode(storageproductsdata[index]["productUnitCode"]);
            }
            //配件数据
            let productsatabledata = storageproductsdata[index].partsList;
            if(typeof productsatabledata != "undefined" && productsatabledata != ""){
                $.each(productsatabledata, function (i, value) {
                    if (typeof (productsatabledata[i]["partsCode"]) == "undefined" || productsatabledata[i]["partsCode"] == "") {
                        layer.msg("产品表第" + (index + 1) + "条中对应产品规格配件表第" + (i + 1) + "条配件编码不能为空");
                        indexsl++;
                        return false;
                    } else if (typeof (productsatabledata[i]["proportionFinishedProducts"]) == "undefined" || productsatabledata[i]["proportionFinishedProducts"] == "") {
                        layer.msg("产品表第" + (index + 1) + "条中对应产品规格配件表第" + (i + 1) + "条成品比例不能为空");
                        indexsl++;
                        return false;
                    } else if (typeof (productsatabledata[i]["partsFinishedProducts"]) == "undefined" || productsatabledata[i]["partsFinishedProducts"] == "") {
                        layer.msg("产品表第" + (index + 1) + "条中对应产品规格配件表第" + (i + 1) + "条配件比例不能为空");
                        indexsl++;
                        return false;
                    }
                });
            }
            if(indexsl > 0){
                return false;
            }
        });
        if (indexsl == 0) {
            $.each(costtabledata, function (index, value) {
                if (typeof (costtabledata[index]["typeCode"]) == "undefined" || costtabledata[index]["typeCode"] == "") {
                    layer.msg("费用表第" + (index + 1) + "条费用类型不能为空");
                    indexsl++;
                    return false;
                } else if (typeof (costtabledata[index]["amount"]) == "undefined" || costtabledata[index]["amount"] == "") {
                    layer.msg("费用表第" + (index + 1) + "条金额不能为空");
                    indexsl++;
                    return false;
                }
            });
        }

        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        if (indexsl == 0) {
            req["detailList"] = storageproductsdata;

            req["costList"] = costtabledata;

            //获取附件数据
            let annexReqs = table.cache["attachmenttableid"];
            req["annexList"] = annexReqs;
            req["deleteAnnexIds"] = deleteAnnexIds;

            let datas = JSON.stringify(req);
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:datas,
                url:"task/add",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/ExportBusiness/task.jsp");
                            parent.intab("views/jsp/ExportBusiness/task.jsp", "任务(备货合同)")
                            parent.detab("views/jsp/ExportBusiness/tpl/newuptask.jsp" + (id == '' ? '' : '?id=' + id));
                        }, );
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    return false;
                }
            });

        }
        return false;
    });

    //计算预收款金额:预收款金额=合同总额*预收款比例/100
    function getAdvancePaymentAmount(advancePaymentRatio){
        //合同总额
        let totalContractAmount = $("#totalContractAmount").val();
        if (!isNumber(totalContractAmount)) {
            totalContractAmount = 0;
        }
        //预收款金额=合同总额*预收款比例/100
        let sum = new BigNumber(totalContractAmount).multipliedBy(advancePaymentRatio).dividedBy(100);
        //预收款金额:四舍五入保留2位小数
        return sum.dp(2, BigNumber.ROUND_HALF_UP).toString();
    }

    //计算预收款比例:预收款比例=预收款金额/合同总额*100
    function getAdvancePaymentRatio(advancePaymentAmount){
        //合同总额
        let totalContractAmount = $("#totalContractAmount").val();
        if (!isNumber(totalContractAmount)) {
            totalContractAmount = 0;
        }
        //预收款比例=合同总额/预收款金额*100
        let sum = new BigNumber(advancePaymentAmount).dividedBy(totalContractAmount).multipliedBy(100);
        //预收款比例:四舍五入保留2位小数
        return sum.dp(2, BigNumber.ROUND_HALF_UP).toString();
    }
    //预收款比例改变时，重新计算预收款金额:预收款金额=合同总额*预收款比例/100
    $('#advancePaymentRatio').bind('input propertychange', function() {
        //预收款比例
        let advancePaymentRatio = $("#advancePaymentRatio").val();
        if (!isNumber(advancePaymentRatio)) {
            layer.msg('请输入数字');
            return;
        }
        if(advancePaymentRatio > 100){
            layer.msg('预收款比例不能超过100');
            $("#advancePaymentRatio").val("0");
            return;
        }
        //预收款金额
        let advancePaymentAmount = getAdvancePaymentAmount(advancePaymentRatio);
        $("#advancePaymentAmount").val(advancePaymentAmount);
        //记录用户最后一次输入的那个值: 1.预收款比例 2.预收款金额
        advancePayment = 1;
    });

    //预收款金额改变时，重新计算预收款比例:预收款比例=预收款金额/合同总额*100
    $('#advancePaymentAmount').bind('input propertychange', function() {
        //预收款金额
        let advancePaymentAmount = $("#advancePaymentAmount").val();
        if (!isNumber(advancePaymentAmount)) {
            layer.msg('请输入数字');
            return;
        }
        //预收款比例
        let advancePaymentRatio = getAdvancePaymentRatio(advancePaymentAmount);
        $("#advancePaymentRatio").val(advancePaymentRatio);
        //记录用户最后一次输入的那个值: 1.预收款比例 2.预收款金额
        advancePayment = 2;
    });

//--产品信息
    let initData = [];
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: initData,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'img', title: '产品图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'productCode', width: 220, title: '产品编码', templet:'#productcodeselect',style:"color:#009688"},
            {field: 'specificationCode', width: 120, title: '规格编码', edit: 'text'},
            {field: 'specificationExplanation', width: 120, title: '规格说明', edit: 'text'},
            {field: 'clientProductNo', width: 120, title: '客户货号', edit: 'text'},
            {field: 'productCname', width: 120, title: '中文名称', edit: 'text'},
            {field: 'productEname', width: 120, title: '英文名称', edit: 'text'},
            {field: 'productCdesc', width: 120, title: '中文描述', edit: 'text'},
            {field: 'productEdesc', width: 120, title: '英文描述', edit: 'text'},
            {field: 'productNum', width: 120, title: '数量', edit: 'text', totalRow: true},
            {field: 'productUnitCode', width: 120, title: '单位', templet: '#unitselect'},
            {field: 'unitPrice', width: 150, title: '单价', edit: 'text'},
            {field: 'moneySubtotal', width: 120, title: '金额小计', edit: 'text', totalRow: true},
            {field: 'deliveryDate', width: 150, title: '要求交货日期', templet:function(d){
                    return '<input type="text" value="'+d.deliveryDate+'"  class="layui-input layui-input-date">';
                }},
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称', edit: 'text'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号', edit: 'text'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码', edit: 'text'},
            {field: 'color', width: 120, title: '颜色', edit: 'text'},
            {field: 'customsCode', width: 120, title: '海关编码', templet: '#customscodeselect'},
            {field: 'nameCustomsDeclaration', width: 120, title: '报关品名', edit: 'text'},
            {field: 'englishProductName', width: 120, title: '英文品名', edit: 'text'},
            {field: 'customsDeclarationUnit', width: 120, title: '报关单位', edit: 'text'},
            {field: 'importTariffs', width: 120, title: '进口关税', edit: 'text'},
            {field: 'taxRebateRate', width: 120, title: '退税率', edit: 'text'},
            {field: 'vatRate', width: 120, title: '增值税率', edit: 'text'},
            {field: 'outerPackingLong', title: '外包装长', width: 120, edit: 'text'},
            {field: 'outerPackingWide', title: '外包装宽', width: 120, edit: 'text'},
            {field: 'outerPackingHeight', title: '外包装高', width: 120, edit: 'text'},
            {field: 'outerPackingExplain', title: '外包装说明', width: 120, edit: 'text'},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            hoverOpenImg();//显示大图

            $(".layui-input-date").each((i,e)=>{
                laydate.render({
                    elem:e,
                    format: 'yyyy-MM-dd',
                    type: 'date',
                    trigger: 'click',
                    theme: '#393D49',
                    calendar: true,
                    done(data){
                        let tableData = table.cache["storageproductstableid"];
                        tableData[i]["deliveryDate"] = data;
                        table.reload('storageproductstableid',{data:tableData});
                    }
                });
            })

            for(let i in customsCode){
                $(".customsCode").append("<option value=\"" + customsCode[i].code + "\">" + customsCode[i].code + "_" + customsCode[i].name + "</option>");
            }
            for(let i in unitOfQuantity){
                $(".productUnitCode").append("<option value=\"" + unitOfQuantity[i].code + "\">" + unitOfQuantity[i].name + "</option>");
            }
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                let classs = ".y_" + tempId;
                $(classs).ySearchSelect(classs);
                if(!isEmpty(res.data[i].productUnitCode)){
                    $("#productUnitCode_" + tempId).val(res.data[i].productUnitCode);
                }else {
                    let unit = unitOfQuantity[0].code;
                    res.data[i].productUnitCode = unit;
                    $("#productUnitCode_" + tempId).val(unit);
                }

                //海关相关信息
                if(!isEmpty(res.data[i].customsCode)){
                    $("#customsCode_" + tempId).val(res.data[i].customsCode);
                }

                //金额小计
                let moneySubtotal = res.data[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }
            //sum(费用)
            let costData = table.cache["costtableid"];
            let sumAmount = 0;
            for(let i in costData){
                let amount = costData[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let totalContractAmount = new BigNumber(sumMoneySubtotal).plus(sumAmount).dp(2, BigNumber.ROUND_HALF_UP).toString();
            $("#totalContractAmount").val(totalContractAmount);
            form.render('select');
        }
    });

    form.on("select(customscodeselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["customsCode"] = data.value;
                for(let i in customsCode){
                    if(customsCode[i].code == data.value){
                        //报关品名
                        tableData[index]["nameCustomsDeclaration"] = customsCode[i].name;
                        //英文品名
                        tableData[index]["englishProductName"] = customsCode[i].englishName;
                        //报关单位
                        tableData[index]["customsDeclarationUnit"] = customsCode[i].unitOfQuantity;
                        //进口关税
                        tableData[index]["importTariffs"] = customsCode[i].importTariff;
                        //退税率
                        tableData[index]["taxRebateRate"] = customsCode[i].taxRate;
                        //增值税率
                        tableData[index]["vatRate"] = customsCode[i].vatRate;
                    }
                }
            }
        });
        table.reload('storageproductstableid',{data:tableData});
    });
    form.on("select(unitselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["productUnitCode"] = data.value;
                tableData[index]["productUnitName"] = getProductUnitCode(data.value);
            }
        });
    });
    function getProductUnitCode(code){
        for(let i in unitOfQuantity){
            if(unitOfQuantity[i].code == code){
                return unitOfQuantity[i].name;
            }
        }
        return "";
    }

    function productTableReload(){
        table.reload('storageproductstableid',{
            data:table.cache.test,
            totalRow: true,
        })
    }

    table.on('edit(storageproductstable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "productNum" ||
            obj.field == "unitPrice" ||
            obj.field == "moneySubtotal" ||
            obj.field == "outerPackingLong" ||
            obj.field == "outerPackingWide" ||
            obj.field == "outerPackingHeight" ||
            obj.field == "importTariffs" ||
            obj.field == "taxRebateRate" ||
            obj.field == "vatRate") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.field == "productNum"){
            //数量(数量变更，对应金额小计、合同总额、预收款比例、预收款金额、配件数量重新计算)
            let productNum = obj.value;
            /*//剩余数量
            let remainingQuantity = obj.data["remainingQuantity"];
            if(!isEmpty(remainingQuantity)){
                let flag = new BigNumber(remainingQuantity).gte(productNum);
                if(!flag){
                    layer.msg('数量不能超过剩余可用数量！');
                    $(this).val(old);
                    return;
                }
            }*/
            obj.data.productNum = productNum;

            //1.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;

            //2.合同总额:sum(金额小计)+sum(费用)
            let totalContractAmount = getTotalContractAmount(obj.data, moneySubtotal);
            $("#totalContractAmount").val(totalContractAmount);

            //3.预收款比例、预收款金额
            getAdvancePaymentRatioOrAmount();

            //4.配件数量:对应产品数量*配件比例
            let partsList = obj.data.partsList;
            if(!isEmpty(partsList) && partsList.length > 0){
                for(let i in partsList){
                    //配件比例
                    let partsFinishedProducts = partsList[i].partsFinishedProducts;
                    let sum = new BigNumber(productNum).multipliedBy(partsFinishedProducts).dp(4, BigNumber.ROUND_HALF_UP).toString();
                    partsList[i]["partsAmount"] = sum;
                }
            }
            //表单重载
            productTableReload();

            table.reload("productsatableid", {data: partsList});

        }
        if(obj.field == "unitPrice"){
            //单价(单价变更，对应金额小计、合同总额、预收款比例、预收款金额重新计算)
            //单价
            let unitPrice = obj.value;
            obj.data.unitPrice = unitPrice;

            //1.金额小计:单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;

            //2.合同总额:sum(金额小计)+sum(费用)
            let totalContractAmount = getTotalContractAmount(obj.data, moneySubtotal);
            $("#totalContractAmount").val(totalContractAmount);

            //3.预收款比例、预收款金额
            getAdvancePaymentRatioOrAmount();
            //表单重载
            productTableReload();
        }
        if(obj.field == "moneySubtotal"){
            //金额小计(金额小计变更，对应合同总额、预收款比例、预收款金额重新计算)
            let moneySubtotal = obj.value;
            obj.data.moneySubtotal = moneySubtotal;

            //1.合同总额:sum(金额小计)+sum(费用)
            let totalContractAmount = getTotalContractAmount(obj.data, moneySubtotal);
            $("#totalContractAmount").val(totalContractAmount);

            //2.预收款比例、预收款金额
            getAdvancePaymentRatioOrAmount();

            //表单重载
            productTableReload();
        }
    });

    //计算预收款比例或金额
    function getAdvancePaymentRatioOrAmount(){
        //预收款比例
        let advancePaymentRatio = $("#advancePaymentRatio").val();
        //预收款金额
        let advancePaymentAmount = $("#advancePaymentAmount").val();
        switch (advancePayment) {
            case 0:
                if(!isEmpty(advancePaymentRatio)){
                    //预收款比例不为空，则计算预收款金额:预收款金额=合同总额*预收款比例/100
                    let amount = getAdvancePaymentAmount(advancePaymentRatio);
                    $("#advancePaymentAmount").val(amount);
                }else if(!isEmpty(advancePaymentAmount)){
                    //预收款金额不为空，则计算预收款比例:预收款比例=合同总额/预收款金额*100
                    let ratio = getAdvancePaymentRatio(advancePaymentAmount);
                    $("#advancePaymentRatio").val(ratio);
                }
                break;
            case 1:
                //确定用户最后一次填写了预收款比例
                let amount = getAdvancePaymentAmount(advancePaymentRatio);
                $("#advancePaymentAmount").val(amount);
                break;
            case 2:
                //确定用户最后一次填写了预收款金额
                let ratio = getAdvancePaymentRatio(advancePaymentAmount);
                $("#advancePaymentRatio").val(ratio);
                break;
        }
        return;
    }

    //合同总额:sum(金额小计)+sum(费用)
    function getTotalContractAmount(data, currentData){
        let productData = table.cache["storageproductstableid"];
        //sum(金额小计)
        let sumMoneySubtotal = 0;
        for(let i in productData){
            if(productData[i].tempId == data.tempId){
                continue;
            }
            //金额小计
            let moneySubtotal = productData[i].moneySubtotal;
            if(!checkNumber(moneySubtotal)){
                moneySubtotal = 0;
            }
            sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
        }
        //sum(费用)
        let costData = table.cache["costtableid"];
        let sumAmount = 0;
        for(let i in costData){
            let amount = costData[i].amount;
            if(!checkNumber(amount)){
                amount = 0;
            }
            sumAmount = new BigNumber(sumAmount).plus(amount);
        }
        let sum = new BigNumber(sumMoneySubtotal).plus(sumAmount).plus(currentData).dp(2, BigNumber.ROUND_HALF_UP).toString();
        return sum;
    }

    //金额小计:单价*数量
    function getMoneySubtotal(data){
        //单价
        let unitPrice = data.unitPrice;
        if(!checkNumber(unitPrice)){
            unitPrice = 0;
        }
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            productNum = 0;
        }

        let sum = new BigNumber(unitPrice).multipliedBy(productNum);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //产品明细单个删除
    table.on('tool(storageproductstable)', function (obj) {
        let data = obj.data;
        let oldData =  table.cache["storageproductstableid"];
        if (obj.event === 'del') {
            layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                for(let i in oldData){
                    if(oldData[i].tempId == data.tempId){
                        oldData.splice(i, 1);
                        table.reload('storageproductstableid',{data : oldData});
                        let defData = [];
                        table.reload("productsatableid", {data: defData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    function tobottomfn(id){
        let d=$("[lay-id='"+id+"'] .layui-table-main").get(0)
        let h=d.scrollHeight
        d.scrollTo(0,h)
    }

    table.on('toolbar(storageproductstable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'importproducts':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/productlibraryimport.jsp?tableid=storageproductstableid&modelId=offer'
                });
                break;
            case 'new':
                let oldData = table.cache["storageproductstableid"];
                let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
                let deliveryDate = $("#carryTime").val();
                if(isEmpty(deliveryDate)){
                    deliveryDate = currentDate;
                }
                let newData = {
                    "tempId": tempId,
                    "productNum": 0,
                    "unitPrice" : 0,
                    "moneySubtotal" : 0,
                    "purchasePriceUsd" : 0,
                    "profitMargin" : 0,
                    "warehouseCostRatio" : 0,
                    "fortyOceanFreight" : 0,
                    "fortyHq" : 0,
                    "marginalProfitRatio" : 0,
                    "warehouseCostAmount" : 0,
                    "profitMarginRatio" : 0,
                    "importTariffs" : 0,
                    "taxRebateRate" : 0,
                    "vatRate" : 0,
                    "deliveryDate" : deliveryDate
                };
                oldData.push(newData);
                table.reload('storageproductstableid', {data: oldData, limit:oldData.length});
                tobottomfn("storageproductstableid");
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                        let cbList = table.cache["storageproductstableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("storageproductstableid", {
                            data: cbList,
                        });
                        let defData = [];
                        table.reload("productsatableid", {data: defData});
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    //监听行单击事件 配件表
    table.on('row(storageproductstable)', function (obj) {
        $("#hidden").show();
        partsParentTempId = obj.data.tempId;
        let initParts = [];
        if(!isEmpty(obj.data.partsList)){
            initParts = obj.data.partsList;
        }
        table.render({
            elem: '#productsaselect'
            , data: initParts
            , toolbar: '#productsatoolbar'
            , where: {id: obj.data.id} //查询的产品ID，条件
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'partsCode', title: '配件编码', edit: 'text'}
                , {field: 'specNo', title: '规格编码', edit: 'text'}
                , {field: 'proportionFinishedProducts', title: '成品比例', edit: 'text'}
                , {field: 'partsFinishedProducts', title: '配件比例', edit: 'text'}
                , {field: 'partsAmount', title: '数量', edit: 'text'}
                , {field: 'productCname', title: '中文名称', edit: 'text'}
                , {field: 'productEname', title: '英文名称', edit: 'text'}
                , {field: 'grossWeight', title: '毛重', edit: 'text'}
                , {field: 'netWeight', title: '净重', edit: 'text'}
                , {field: 'bulk', title: '体积', edit: 'text'}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#productsaup', title: '操作'}
            ]]
            , id: 'productsatableid'
            ,page: false
            ,limit: Number.MAX_VALUE
            , height: 300
        });

    });

    table.on('edit(productsatable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "proportionFinishedProducts" ||
            obj.field == "partsFinishedProducts" ||
            obj.field == "partsAmount" ||
            obj.field == "grossWeight" ||
            obj.field == "netWeight" ||
            obj.field == "bulk") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        let parentTable = table.cache["storageproductstableid"];
        for(let k in parentTable){
            if(parentTable[k].tempId == partsParentTempId){
                let partsList = parentTable[k].partsList;
                let productNum = parentTable[k].productNum;
                for(let j in partsList){
                    if(partsList[j].tempId == obj.data.tempId){
                        if(obj.field == "partsFinishedProducts"){
                            //配件比例
                            partsList[j]["partsFinishedProducts"] = obj.value;
                            let sum = new BigNumber(productNum).multipliedBy(obj.value).dp(4, BigNumber.ROUND_HALF_UP).toString();
                            partsList[j]["partsAmount"] = sum;
                            break;
                        }
                        if(obj.field == "partsCode"){
                            //配件编码
                            partsList[j]["partsCode"] = obj.value;
                            break;
                        }
                        if(obj.field == "specNo"){
                            //规格编码
                            partsList[j]["specNo"] = obj.value;
                            break;
                        }
                        if(obj.field == "proportionFinishedProducts"){
                            //成品比例
                            partsList[j]["proportionFinishedProducts"] = obj.value;
                            break;
                        }
                        if(obj.field == "partsAmount"){
                            //数量
                            partsList[j]["partsAmount"] = obj.value;
                            break;
                        }
                        if(obj.field == "productCname"){
                            //中文名称
                            partsList[j]["productCname"] = obj.value;
                            break;
                        }
                        if(obj.field == "productEname"){
                            //英文名称
                            partsList[j]["productEname"] = obj.value;
                            break;
                        }
                        if(obj.field == "grossWeight"){
                            //毛重
                            partsList[j]["grossWeight"] = obj.value;
                            break;
                        }
                        if(obj.field == "netWeight"){
                            //净重
                            partsList[j]["netWeight"] = obj.value;
                            break;
                        }
                        if(obj.field == "bulk"){
                            //体积
                            partsList[j]["bulk"] = obj.value;
                            break;
                        }
                    }
                }
                parentTable[k]["partsList"] = partsList;
                table.reload("storageproductstableid", {data: parentTable});
                table.reload("productsatableid", {data: partsList});
                break;
            }
        }
    });


    table.on('toolbar(productsatable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'new':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/productlibraryimport.jsp?tableid=productsatableid&modelId=offer&partsParentTempId='+partsParentTempId
                });
                break;
            case 'delet':
                var data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', function (index) {
                        let cbList = table.cache["productsatableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        //删除对应配件信息
                        deleteProductParts(cbList);
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    //删除对应配件信息
    function deleteProductParts(oldData){
        let parentTable = table.cache["storageproductstableid"];
        for(let k in parentTable){
            if(parentTable[k].tempId == partsParentTempId){
                parentTable[k]["partsList"] = oldData;
                break;
            }
        }
        table.reload("storageproductstableid", {
            data: parentTable
        });
        table.reload("productsatableid", {
            data: oldData
        });
    }

    //配件表单个删除
    table.on('tool(productsatable)', function (obj) {
        let data = obj.data;
        let oldData =  table.cache["productsatableid"];
        if (obj.event === 'productsade') {
            layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                for(let i in oldData){
                    if(oldData[i].tempId == data.tempId){
                        oldData.splice(i, 1);
                        break;
                    }
                }
                //将对应配件信息删除
                deleteProductParts(oldData);
                layer.msg('删除成功');
                layer.close(index);
            });
        }
    });

    //---费用
    let initCost = [];
    table.render({
        elem: '#cost'
        , data: initCost
        , toolbar: '#costtoolbar'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'typeCode', title: '费用类型', templet: '#costtypeselect'}
            , {field: 'amount', title: '金额', event: 'amount', edit: 'text'}
            , {field: 'memo', title: '备注说明', edit: 'text'}
        ]]
        , id: 'costtableid'
        , height: 380
        ,page: false
        ,limit: Number.MAX_VALUE
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            for(let i in costType){
                $(".typeCode").append("<option value=\"" + costType[i].code + "\">" + costType[i].name + "</option>");
            }
            //sum(费用)
            let sumAmount = 0;
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                $("#typeCode_" + tempId).val(res.data[i].typeCode);

                let amount = res.data[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let productData = table.cache["storageproductstableid"];
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for(let i in productData){
                //金额小计
                let moneySubtotal = productData[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }
            //合同总额=sum(金额小计)+sum(费用)
            let totalContractAmount = new BigNumber(sumMoneySubtotal).plus(sumAmount).dp(2, BigNumber.ROUND_HALF_UP).toString();
            $("#totalContractAmount").val(totalContractAmount);

            //预收款比例、预收款金额
            getAdvancePaymentRatioOrAmount();

            form.render('select');
        }
    });
    table.on('edit(costtable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "amount") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.field == "amount"){
            //重新计算合同总额
            let productData = table.cache["storageproductstableid"];
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for(let i in productData){
                //金额小计
                let moneySubtotal = productData[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }

            //sum(费用)
            let costData = table.cache["costtableid"];
            let sumAmount = 0;
            for(let i in costData){
                if(costData[i].tempId == obj.data.tempId){
                    continue;
                }
                let amount = costData[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let totalContractAmount = new BigNumber(sumMoneySubtotal).plus(sumAmount).plus(obj.value).dp(4, BigNumber.ROUND_HALF_UP).toString();
            $("#totalContractAmount").val(totalContractAmount);

            //预收款比例、预收款金额
            getAdvancePaymentRatioOrAmount();

            form.render();
        }
    });

    form.on("select(costtypeselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["costtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["typeCode"] = data.value;
                tableData[index]["typeName"] = getTypeNameByCode(data.value);
            }
        });
    });

    function getTypeNameByCode(code){
        for(let i in costType){
            if(costType[i].code == code){
                return costType[i].name;
            }
        }
        return "";
    }

    table.on('toolbar(costtable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'new':
                let oldData = table.cache["costtableid"];
                let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
                let newData = {
                    "tempId" : tempId,
                    "typeCode" : "",
                    "amount" : 0,
                    "memo" : ""
                };
                oldData.push(newData);
                table.reload('costtableid', {data: oldData, limit:oldData.length});
                tobottomfn("costtableid");
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？',confirmInfo(3,6), function (index) {
                        var cbList = table.cache["costtableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("costtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });


    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true, sort:true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            if(0 == annexList[i]["news"]){
                                //记录被删除的老的附件
                                deleteAnnexIds.push(id);
                            }
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        } else if (obj.event === 'fileName') {
            onLineFile(data.filePath);
        }
    });

//---操作日志
    let initOperation = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: initOperation
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    //签约日期
    laydate.render({
        elem: '#signingDate',
        value: currentDate,
        isInitValue: true
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    function checkNumber(val) {
        if(isEmpty(val)){
            return false;
        }
        if(!isNumber(val)){
            return false;
        }
        return true;
    }

});

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}
let currentDate = getNowFormatDate(1);

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

function setHSInfo(data){
    for(let j in customsCode){
        if(customsCode[j].code == data.customsCode){
            //报关品名
            data["nameCustomsDeclaration"] = customsCode[j].name;
            //英文品名
            data["englishProductName"] = customsCode[j].englishName;
            //报关单位
            data["customsDeclarationUnit"] = customsCode[j].unitOfQuantity;
            //进口关税
            data["importTariffs"] = customsCode[j].importTariff;
            //退税率
            data["taxRebateRate"] = customsCode[j].taxRate;
            //增值税率
            data["vatRate"] = customsCode[j].vatRate;

            return data;
        }
    }
}